package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Linked;
import cn.edu.seu.herald.informationplatform.bean.league.Picture;
import cn.edu.seu.herald.informationplatform.dao.database.PictureDao;

public class AlbumPicturesRequired implements Filter {
	
	public static final String PARAM_NAME_OF_ALBUM_ID = "album";

	public static final String PICTURES_BEAN_NAME = "pictures";
	
	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		try {
			String albumIdParam = request.getParameter(
					PARAM_NAME_OF_ALBUM_ID);
			PictureDao access = PictureDao.getDao();
			Map<Integer, Picture> pictureMap =
					access.getPicturesByAlbumId(Integer.valueOf(albumIdParam));
			Collection<Linked<Picture>> pictures =
					new LinkedList<Linked<Picture>>();
			for (Entry<Integer, Picture> e: pictureMap.entrySet()) {
				int key = e.getKey();
				Picture value = e.getValue();
				
				Linked<Picture> p = new Linked<Picture>();
				p.setEntity(value);
				p.setLink(String.valueOf(key));
				pictures.add(p);
			}
			httpRequest.setAttribute(PICTURES_BEAN_NAME, pictures);
		} catch (NumberFormatException e) {
			httpResponse.sendError(400);
			return;
		} catch (SQLException e) {
			httpResponse.sendError(500);
			return;
		}
		chain.doFilter(request, response);
	}

}
